<template>
  <div class="source-management-container">
    <div class="page-header">
      <h1>来源管理</h1>
      <p>管理系统中的各种来源定义，如需求来源、缺陷来源等。</p>
    </div>

    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>来源列表</span>
          <div class="header-actions">
            <el-button type="success" @click="handleInitialize">初始化默认数据</el-button>
            <el-button type="primary" @click="handleAddSource">添加来源</el-button>
            <el-button @click="handleRefreshCache">刷新缓存</el-button>
          </div>
        </div>
      </template>

      <!-- 筛选工具栏 -->
      <div class="filter-toolbar">
        <el-select
          v-model="filterModuleType"
          placeholder="选择模块"
          clearable
          style="width: 160px"
          @change="handleFilterChange"
        >
          <el-option label="全部模块" value="" />
          <el-option
            v-for="module in moduleTypes"
            :key="module.value"
            :label="module.label"
            :value="module.value"
          />
        </el-select>
        <el-checkbox v-model="includeDisabled" @change="handleFilterChange">
          显示已禁用
        </el-checkbox>
      </div>

      <el-table 
        :data="sourceList" 
        v-loading="loading" 
        border 
        stripe
        table-layout="auto"
        fit
        style="width: 100%"
      >
        <el-table-column prop="name" label="来源名称" min-width="150" align="left">
          <template #default="{ row }">
            <el-tag 
              :color="row.color" 
              style="color: white; border: none;"
              :style="{ maxWidth: '100%' }"
              class="source-name"
            >
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="编码" min-width="120" align="center" />
        <el-table-column prop="module_type" label="所属模块" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.module_type" :type="getModuleTagType(row.module_type)" size="small">
              {{ getModuleLabel(row.module_type) }}
            </el-tag>
            <span v-else class="text-muted">通用</span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="description" 
          label="描述" 
          min-width="200" 
          align="left"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.description">{{ row.description }}</span>
            <span v-else class="text-muted">无描述</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" align="center" />
        <el-table-column prop="is_enabled" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_enabled ? 'success' : 'danger'" size="small">
              {{ row.is_enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              :type="row.is_enabled ? 'warning' : 'success'" 
              link 
              @click="handleToggleStatus(row)"
            >
              {{ row.is_enabled ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 来源表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑来源' : '添加来源'"
      :width="isMobile ? '90%' : '500px'"
      :before-close="handleClose"
    >
      <el-form
        ref="sourceFormRef"
        :model="sourceForm"
        :rules="sourceRules"
        label-width="100px"
      >
        <el-form-item label="来源名称" prop="name">
          <el-input v-model="sourceForm.name" placeholder="请输入来源名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="来源编码" prop="code">
          <el-input v-model="sourceForm.code" placeholder="请输入来源编码（唯一标识）" maxlength="50" show-word-limit :disabled="isEditing" />
        </el-form-item>
        <el-form-item label="所属模块" prop="module_type">
          <el-select
            v-model="sourceForm.module_type"
            placeholder="选择模块"
            style="width: 100%"
          >
            <el-option
              v-for="module in moduleTypes"
              :key="module.value"
              :label="module.label"
              :value="module.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="sourceForm.color" :predefine="predefineColors" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="sourceForm.sort_order" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="is_enabled">
          <el-switch v-model="sourceForm.is_enabled" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="sourceForm.description"
            type="textarea"
            placeholder="请输入来源描述"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSaveSource"
            :loading="saving"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { sourceApi } from '@/api/source'
import type { Source } from '@/api/source'
import { MODULE_TYPES, getModuleLabel } from '@/utils/moduleTypes'

// 响应式数据
const sourceList = ref<Source[]>([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)
const sourceFormRef = ref<FormInstance>()

// 筛选条件
const filterModuleType = ref<string>('')
const includeDisabled = ref(false)

// 模块类型配置
const moduleTypes = MODULE_TYPES

// 预定义颜色列表
const predefineColors = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
  '#1890FF', '#52C41A', '#FAAD14', '#F5222D', '#722ED1',
  '#13C2C2', '#EB2F96', '#FA8C16', '#A0D911', '#2F54EB'
]

// 响应式设计
const isMobile = computed(() => {
  return window.innerWidth < 768
})

// 来源表单
const sourceForm = reactive({
  id: '',
  name: '',
  code: '',
  module_type: '',
  description: '',
  color: '#409EFF',
  sort_order: 0,
  is_enabled: true
})

// 表单验证规则
const sourceRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入来源名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入来源编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '编码只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  module_type: [
    { required: true, message: '请选择所属模块', trigger: 'change' }
  ],
  color: [
    { required: true, message: '请选择来源颜色', trigger: 'change' }
  ]
})

// 获取来源列表
const fetchSources = async () => {
  try {
    loading.value = true
    const res = await sourceApi.getAll(filterModuleType.value || undefined, includeDisabled.value)
    if (res && res.success) {
      // 即使 data 是空数组也是正常的，直接赋值
      sourceList.value = Array.isArray(res.data) ? res.data : []
    } else {
      // 只有当 success 为 false 时才显示错误
      ElMessage.error(res?.message || '获取来源列表失败')
      sourceList.value = []
    }
  } catch (error) {
    console.error('获取来源列表失败:', error)
    ElMessage.error('获取来源列表失败')
    sourceList.value = []
  } finally {
    loading.value = false
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  fetchSources()
}

// 刷新缓存
const handleRefreshCache = async () => {
  try {
    const res = await sourceApi.refreshCache()
    if (res.success) {
      ElMessage.success('缓存刷新成功')
      fetchSources()
    } else {
      ElMessage.error(res.message || '缓存刷新失败')
    }
  } catch (error) {
    console.error('缓存刷新失败:', error)
    ElMessage.error('缓存刷新失败')
  }
}

// 初始化默认数据
const handleInitialize = async () => {
  try {
    // 检查是否选择了模块
    if (!filterModuleType.value) {
      ElMessage.warning('请先选择要初始化的模块类型')
      return
    }
    
    // 确认操作
    await ElMessageBox.confirm(
      `确定要为 "${getModuleLabel(filterModuleType.value as any)}" 模块初始化默认来源数据吗?`,
      '初始化确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用初始化接口
    const res = await sourceApi.initialize(filterModuleType.value)
    if (res.success) {
      const count = res.data?.created_count || 0
      ElMessage.success(res.message || `成功初始化 ${count} 个默认来源`)
      fetchSources()
    } else {
      ElMessage.error(res.message || '初始化失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('初始化失败:', error)
      ElMessage.error('初始化失败')
    }
  }
}

// 获取模块标签类型
const getModuleTagType = (moduleType: string): string => {
  const module = moduleTypes.find(m => m.value === moduleType)
  if (!module) return ''
  const colorMap: Record<string, string> = {
    'blue': 'primary',
    'green': 'success',
    'orange': 'warning',
    'red': 'danger',
    'purple': '',
    'geekblue': 'info',
    'cyan': 'info'
  }
  return colorMap[module.color] || ''
}

// 处理添加来源
const handleAddSource = () => {
  isEditing.value = false
  Object.assign(sourceForm, {
    id: '',
    name: '',
    code: '',
    module_type: filterModuleType.value || '',
    description: '',
    color: '#409EFF',
    sort_order: 0,
    is_enabled: true
  })
  dialogVisible.value = true
}

// 处理编辑来源
const handleEdit = (row: Source) => {
  isEditing.value = true
  Object.assign(sourceForm, {
    id: row.id || row._id || '',
    name: row.name,
    code: row.code,
    module_type: row.module_type,
    description: row.description || '',
    color: row.color || '#409EFF',
    sort_order: row.sort_order || 0,
    is_enabled: row.is_enabled !== false
  })
  dialogVisible.value = true
}

// 处理对话框关闭
const handleClose = () => {
  dialogVisible.value = false
  if (sourceFormRef.value) {
    sourceFormRef.value.resetFields()
  }
}

// 处理保存来源
const handleSaveSource = async () => {
  if (!sourceFormRef.value) return
  
  await sourceFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (isEditing.value) {
          const res = await sourceApi.update(sourceForm.id, {
            name: sourceForm.name,
            description: sourceForm.description,
            color: sourceForm.color,
            sort_order: sourceForm.sort_order,
            is_enabled: sourceForm.is_enabled
          })
          if (res.success) {
            ElMessage.success('来源更新成功')
            dialogVisible.value = false
            fetchSources()
          } else {
            ElMessage.error(res.message || '来源更新失败')
          }
        } else {
          const res = await sourceApi.create({
            name: sourceForm.name,
            code: sourceForm.code,
            module_type: sourceForm.module_type,
            description: sourceForm.description,
            color: sourceForm.color,
            sort_order: sourceForm.sort_order,
            is_enabled: sourceForm.is_enabled
          })
          if (res.success) {
            ElMessage.success('来源添加成功')
            dialogVisible.value = false
            fetchSources()
          } else {
            ElMessage.error(res.message || '来源添加失败')
          }
        }
      } catch (error) {
        console.error('保存来源失败:', error)
        ElMessage.error('保存来源失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 处理状态切换
const handleToggleStatus = async (row: Source) => {
  try {
    const newStatus = !row.is_enabled
    const res = await sourceApi.update(row.id || row._id!, {
      is_enabled: newStatus
    })
    if (res.success) {
      ElMessage.success(`${newStatus ? '启用' : '禁用'}成功`)
      fetchSources()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理删除来源
const handleDelete = async (row: Source) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除来源 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await sourceApi.delete(row.id || row._id!)
    if (res.success) {
      ElMessage.success('来源删除成功')
      fetchSources()
    } else {
      ElMessage.error(res.message || '删除来源失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除来源失败:', error)
      ElMessage.error('删除来源失败')
    }
  }
}

// 监听窗口大小变化
const handleResize = () => {
  // 响应式逻辑会在computed属性中自动更新
}

// 初始化
onMounted(() => {
  fetchSources()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.source-management-container {
  padding: 16px;
  background: #f0f2f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 16px;
}

.page-header h1 {
  font-size: 22px;
  margin: 0 0 6px 0;
  font-weight: 500;
}

.page-header p {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.main-card {
  margin-bottom: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

:deep(.el-table__header-wrapper th) {
  font-weight: 500;
  padding: 12px 10px;
}

:deep(.el-table__body-wrapper td) {
  padding: 10px;
}

.text-muted {
  color: #999;
  font-size: 13px;
}

.filter-toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.source-name {
  font-size: 13px;
  padding: 4px 8px;
  height: auto;
  white-space: normal;
  word-break: break-word;
}

@media (max-width: 768px) {
  .source-management-container {
    padding: 12px;
  }
  
  .card-header {
    padding: 10px 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .header-actions .el-button {
    flex: 1;
  }
}

:deep(.el-button) {
  font-size: 14px;
}

:deep(.el-button--link) {
  padding: 4px 10px;
}
</style>
